package scatter.pay.rest.third;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import scatter.common.pojo.param.BaseParam;
import scatter.common.rest.tools.InterfaceTool;
import scatter.pay.rest.PayConfiguration;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static scatter.pay.rest.controller.PayController.*;

/**
 * <p>
 * 三方支付通知地址帮助类
 * </p>
 *
 * @author yangwei
 * @since 2021-06-27 18:47
 */
@Service
public class ThirdNotifyUrlHelper implements InterfaceTool {


	private static Map<ThirdType,String> urlMap = new HashMap<>();
	static {
		// 来自 scatter.pay.rest.controller.PayThirdController 地址
		urlMap.put(ThirdType.wx_pay, PayConfiguration.CONTROLLER_BASE_PATH + "/pay/wx/pay/notify/{appCode}");
		urlMap.put(ThirdType.wx_refund, PayConfiguration.CONTROLLER_BASE_PATH + "/pay/wx/refund/notify/{appCode}");
	}


	/**
	 * 如：http://xxxx.com
	 */
	@Value("${scatter.pay.third.notify.domain}")
	private String domain;

	public String getNotifyUrl(NotifyUrlParam param){
		String r = urlMap.get(param.getThirdType());
		if (ThirdType.wx_pay == param.getThirdType()) {
			r = r.replace("/{appCode}", Optional.ofNullable(param.getWxAppCode()).map((appCode)-> "/" + appCode).orElse(""));
		}else if (ThirdType.wx_refund == param.getThirdType()) {
			r = r.replace("/{appCode}", Optional.ofNullable(param.getWxAppCode()).map((appCode)-> "/" + appCode).orElse(""));
		}

		return domain + r;
	}
	/**
	 * 三方类型
	 */
	public enum ThirdType{
		wx_pay, // 微信支付
		wx_refund // 微信退款
	}
	@Setter
	@Getter
	public static class NotifyUrlParam extends BaseParam {
		private ThirdType thirdType;

		// 微信appcode thirdType为微信相关类型时必填
		private String wxAppCode;
	}
}
